# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://api.cvrpay.com/makeOrder'
_QUERY_GATEWAY = 'http://api.cvrpay.com/queryOrder'
# 创云微 witch
APP_CONF = {
    '62500032': {
        'API_KEY': 'a6141c28f11b2dc0da2f1fce10d25d14',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 支付宝 wap pay_alipay_wap
# 支付宝扫码 pay_alipay_scan
# 微信 wap pay_weixin_wap
# 微信扫码 pay_weixin_scan
# QQ 钱包 wap pay_qq_wap
# QQ 钱包扫码 pay_qq_scan
# 京东钱包 wap pay_jd_wap
# 京东钱包扫码 pay_jd_scan
# 银联支付 pay_bank_wap
def _get_pay_type(service):
    if service == 'alipay':
        return 'pay_alipay_wap'
    elif service == 'wxpay':
        return 'pay_weixin_wap'
    elif service == 'qq':
        return 'pay_qq_wap'
    elif service == 'jd':
        return 'pay_jd_wap'
    else:
        return 'pay_bank_wap'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s = s[0: len(s) - 1]
    s += key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_notify_sign(parameter, key):
    '''  生成下单签名 '''
    s = 'app_id={}&orderid={}&platform_order_id={}&app_order_id={}&pay_type={}&fee={}&unit={}&status={}{}'.format(
        parameter['app_id'], parameter['orderid'], parameter['platform_order_id'], parameter['app_order_id'],
        parameter['pay_type'], parameter['fee'], parameter['unit'], parameter['status'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("easypay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('subject', 'charge'),
        ('total_fee', str(int(pay_amount * 100))),
        ('body', 'charge123'),
        ('pay_type', _get_pay_type(service)),
        ('appid', app_id),
        ('mchorderid', str(pay.id)),
        ('ip', _get_device_ip(info)),
        ('notify_url', '{}/pay/api/{}/easypay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("easypay create  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("easypay create  rsp: %s", response.text)
    j = json.loads(response.text)
    return {'charge_info': j['content']}


# success
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("easypay notify data: %s", data)
    _LOGGER.info("easypay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['app_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('easypay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['status']
    trade_no = data['orderid']
    total_fee = float(data['fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'success':
        _LOGGER.info('easypay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('app_id', app_id),
        ('app_order_id', str(pay_id)),
        ('trade_type', '01'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("easypay query  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("easypay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = data['orderid']
        total_fee = float(data['fee'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0 为失败
        # 1 为成功
        # 2 为处理中
        if trade_status == '1':
            _LOGGER.info('easypay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('easypay data error, status_code: %s', response.status_code)
